$(function () {
    const layer = layui.layer;
    const form = layui.form;
    initArtCateList()

    function initArtCateList() {
        $.ajax({
            type: "GET",
            url: "/my/article/cates",
            success(res) {
                if (res.status !== 0) {
                    return layer.msg("获取列表失败  ")
                }
                console.log(res);
                const htmlStr = template('tel-table', res);
                $("tbody").html(htmlStr);
            }
        })
    }
    let indexAdd = null;
    let indexEdit = null;
    $("#addCategory").on("click", function () {
        indexAdd = layer.open({
            type: 1,
            area: ["500px", "250px"],
            title: '添加文章分类',
            content: $("#dialog-add").html()
        });
    })
    $("body").on("submit", "#form-add", function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/my/article/addcates",
            data: $(this).serialize(),
            success(res) {
                if (res.status !== 0) {
                    return layer.msg(res.message)
                }
                initArtCateList();
                layer.msg(res.message);
                console.log(indexAdd);
                layer.close(indexAdd);
            }
        })
    })
    $("tbody").on("click", "#btn-edit", function (e) {
        e.preventDefault;
        indexEdit = layer.open({
            type: 1,
            area: ["500px", "250px"],
            title: '修改文章分类',
            content: $("#dialog-edit").html()
        });
        const id = $(this).attr("data-id");
        console.log(id);
        $.ajax({
            type: "GET",
            url: "/my/article/cates/" + id,
            success(res) {
                if (res.status !== 0) {
                    return layer.msg(res.message)
                }
                form.val("form-edit", res.data);
            }
        })
    })
    $("body").on("submit", "#form-edit", function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/my/article/updatecate",
            data: $(this).serialize(),
            success(res) {
                if (res.status !== 0) {
                    return layer.msg(res.message)
                }
                layer.msg(res.message);
                layer.close(indexEdit);
                initArtCateList();
            }
        })
    })
    $("tbody").on("click", "#btn-del", function (e) {
        e.preventDefault();
        const id = $(this).attr("data-id");
        layer.confirm('是否删除?', {
            icon: 3,
            title: '提示'
        }, function (index) {
            $.ajax({
                type: "GET",
                url: "/my/article/deletecate/" + id,
                success(res) {
                    layer.msg(res.message);
                    initArtCateList();
                }
            })
            layer.close(index);
        });
    })
})